package com.dream.wuliu.view;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;

import com.beardedhen.androidbootstrap.BootstrapButton;
import com.beardedhen.androidbootstrap.BootstrapEditText;
import com.dream.vo.api.ApiResult;
import com.dream.wuliu.service.AppService;
import com.dream.wuliu.service.ServiceFactory;
import com.dream.wuliu.utils.MyUtils;
@EActivity(R.layout.login)
public class LoginActivity extends BaseActivity {
	
	@ViewById(R.id.etUser)
	BootstrapEditText etUser;
	
	@ViewById(R.id.etPassword)
	BootstrapEditText etPassword;
	
	@ViewById(R.id.btnLogin)
	BootstrapButton btnLogin;
	
	@Click(R.id.btnLogin)
	void loginClick(){
		
		if(validate()){
			//PortalActivity_.intent(this).start();
			login();
		}
		
	}
	
	@Background
	public void login(){
		
		
		final String id = etUser.getText().toString().trim();
		final String password = etPassword.getText().toString().trim();
		
		String gson = new ServiceFactory.AppServiceHelper() {
			@Override
			public ApiResult doService(AppService service) {
				return  service.login(id, password);
			}
		}.execute(this);
		loginResult(gson);
	}
	
	@UiThread
	public void loginResult(String gson){
		
		if(MyUtils.isNotBlank(gson)){
			this.saveGsonUser(gson);
			PortalActivity_.intent(this).start();
		}
		
	}
	
	private boolean validate(){
		
		String user = etUser.getText().toString().trim();
		String pwd = etPassword.getText().toString().trim();
		
		if(user.isEmpty() || user.length() < 4 || user.length() > 30){
			toastMsg("请输入4到30位的用户名!");
			return false;
		}
		
		if(pwd.isEmpty() || pwd.length() < 4 || pwd.length() > 30){
			toastMsg("请输入6到30位的密码!");
			return false;
		}
		
		return true;
		
	}
	
    @AfterViews  
    public void init(){  
    	
    	boolean shortcut = myPrefs.createShortcut().get();
    	if(shortcut){
    		myPrefs.createShortcut().put(false);
    		createShortCut();
    	}
    	etUser.setText("evan");
    	etPassword.setText("123456");
    }  

}

